import React, { useEffect, useState } from 'react';
import ProTable, { ProColumns } from '@ant-design/pro-table';
import {
 getCategoryListByPage,
 getBrandListByPage,
 getGoodsListByPage
} from '@/services/stock-goods/api';
import { getShopGoods } from '@/services/shop/api';
import { MsgType, showMsg } from '@/utils/utils';
import Modal from 'antd/lib/modal/Modal';
import { Button } from 'antd';
import { history, useModel } from 'umi';

const OptForm: React.FC<any> = (props) => {
  const { 
    handleModalVisible
  } = props;

  const { initialState } = useModel('@@initialState');

  const [classList, setClassList] = useState<STOCKGOODSAPI.CategoryItem[]>([]);
  const [brandList, setBrandList] = useState<STOCKGOODSAPI.BrandItem[]>([]);

  const columns: ProColumns<STOCKGOODSAPI.GoodsItem>[] = [
    {
      title: '库存分类',  
      dataIndex: 'class_id',
      valueType: 'select',
      fieldProps: {
        options: classList.map(item => {
          return {
            label: item.class_name as string,
            value: item.class_id as string
          }
        })
      },
      hideInTable: true
    },
    {
      title: '商品品牌',  
      dataIndex: 'brand_id',
      valueType: 'select',
      fieldProps: {
        options: brandList.map(item => {
          return {
            label: item.brand_name as string,
            value: item.brand_id as string
          }
        })
      },
      hideInTable: true
    },
    {
      title: '商品名称',  
      dataIndex: 'goods_name',
      hideInTable: true
    },
    {
      title: '商品编号',  
      dataIndex: 'goods_id',
      hideInTable: true
    },
    {
      title: '品牌',
      dataIndex: 'brand_name',
      search: false
    },
    {
      title: '名称',
      dataIndex: 'goods_name',
      search: false
    },
    {
      title: '编号',
      dataIndex: 'goods_id',
      search: false
    },
    {
      title: '库存',
      dataIndex: 'total_inventry',
      search: false
    },
    {
      title: '规格数',
      dataIndex: 'specs_num',
      search: false
    },
    {
      title: '销量',
      dataIndex: 'salves_volume',
      search: false
    }
  ];

  const [selectedRow, setSelectedRow] = useState<STOCKGOODSAPI.GoodsItem>(null);

  const onAdd = async () => {
    const data = await getShopGoods({
      current: 1,
      pageSize: 1,
      goods_id: selectedRow.goods_id
    })
    
    if (data.record_num) {
      showMsg('该商品已添加，请更换商品', MsgType.INFO);
      return;
    }
    handleModalVisible(false);
    localStorage.setItem('shop-goods-info', JSON.stringify(selectedRow));
    history.push({
      pathname: '/shop/goods/edit'
    });
  }

  useEffect(() => {
    getCategoryListByPage({
      current: 1,
      pageSize: 10000
    }).then((data: STOCKGOODSAPI.CategoryItemList) => {
      const list = data.record_list.filter(item => item.create_dept_code === initialState?.currentUser?.dept_code);
      setClassList(list || []);
    }).catch(error => {
      showMsg(error?.data?.errmsg)
    });

    getBrandListByPage({
      current: 1,
      pageSize: 10000
    }).then((data: STOCKGOODSAPI.BrandItemList) => {
      const list = data.record_list.filter(item => item.create_dept_code === initialState?.currentUser?.dept_code);
      setBrandList(list || []);
    }).catch(error => {
      showMsg(error?.data?.errmsg)
    });
  }, []);

  return <Modal
        className="modal-form"
        width="80%"
        onCancel={() => {
          handleModalVisible(false)
        }}
        bodyStyle={{ height: window.innerHeight-150, overflow: 'scroll' }}
        maskClosable={false}
        title="新增商品"
        visible
        footer={[
            <Button key="cancel" onClick={() => {
              handleModalVisible(false)
            }}>取消</Button>,
            <Button key="add" disabled={!selectedRow} type="primary" onClick={onAdd}>添加至店铺</Button>
          ]}>
      
        <ProTable<STOCKGOODSAPI.GoodsItem, STOCKGOODSAPI.GoodsItem & COMMON.PageParams> 
          rowKey="goods_id"
          bordered
          manualRequest
          options={false}
          search={{
            collapsed: false,
            collapseRender: () => '',
            optionRender: (searchConfig, props, doms) => {
              doms.shift();
              return doms;
            }
          }}
          request={async (params) => {
            try {
              params = Object.assign({}, params, { scope: 'B'});
              const data: STOCKGOODSAPI.GoodsItemList = await getGoodsListByPage(params);
              return {
                data: data.record_list,
                total: data.sum_record_num,
                success: true
              }
            } catch (error) {
              showMsg(error?.data?.errmsg);
              return {
                data: [],
                total: 0,
                success: true
              }
            }
          }}
          rowSelection={{
            type: 'radio',
            onChange: (selectedKeys, selectedRows) => {
              const row = selectedRows[0];
              setSelectedRow(row);
            }
          }}
          pagination={{
            showQuickJumper: true
          }}     
          columns={columns}
        />
      </Modal>
}
export default OptForm;
